package com.flow.framework.lock.service.lock.impl;

import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.lock.service.lock.ILockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * Redisson分布式锁实现类
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/3/13
 */
@Slf4j
@RequiredArgsConstructor
@Deprecated
public class FastLockServiceImpl implements ILockService {

    private final RedissonClient redissonClient;

    @Override
    public boolean tryLock(String lockKey, long waitTime, long leaseTime) {
        try {
            RLock lock = redissonClient.getLock(lockKey);
            return lock.tryLock(waitTime, leaseTime, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            log.error("try lock error. lock key : {}", lockKey, e);
        }
        return false;
    }

    @Override
    public void unlock(String lockKey) {
        try {
            RLock lock = redissonClient.getLock(lockKey);

            //是否还是锁定状态、是否是当前执行线程的锁
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            } else {
                log.error("unlock error. lock key : {}", lockKey);
                throw new CheckedException(SystemErrorCode.LOCK_ERROR, "unlock error");
            }
        } catch (Exception e) {
            log.error("unlock error. lock key : {}", lockKey, e);
            throw new CheckedException(SystemErrorCode.LOCK_ERROR, "unlock error", e);
        }
    }
}
